//
//  SettingController.m
//  TrainTree
//
//  Created by wanghui on 2017/9/11.
//  Copyright © 2017年 YouYeShu. All rights reserved.
//
#import <AVFoundation/AVFoundation.h>
#import "SettingController.h"
#import "MineRequestManager.h"

@interface SettingController ()<UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (weak, nonatomic) IBOutlet UIImageView *iconImageView;
@property (weak, nonatomic) IBOutlet UISwitch *wifiSwitch;
@property (weak, nonatomic) IBOutlet UIButton *exitBtn;

@end

@implementation SettingController

- (void)viewDidLoad {
    [super viewDidLoad];
     self.navigationView.title = @"个人设置";
    self.navigationView.titleIcon.hidden = YES;
    [self.navigationView.leftBtn setImage:ImageNamed(@"close") forState:UIControlStateNormal];
    [self.navigationView.leftBtn addTarget:self action:@selector(backToLastPage) forControlEvents:UIControlEventTouchUpInside];
    [self.iconImageView sd_setImageWithURL:[NSURL URLWithString:self.iconUrl] placeholderImage:ImageNamed(@"ty_pic")];
    [self setCornerAndBorder];
    if ([Session isLogin]) {
        self.exitBtn.hidden = NO;
         ;
    }else{
        self.exitBtn.hidden = YES;

    }
    if ([[USERDEFAULT objectForKey:@"SwitchOpen"] boolValue]) {
        [self.wifiSwitch setOn:YES  animated:YES];

    }else{
        [self.wifiSwitch setOn:NO  animated:YES];

    }

}
- (IBAction)wifiSwitch:(id)sender {
    if ([[USERDEFAULT objectForKey:@"SwitchOpen"] boolValue]) {
        [self.wifiSwitch setOn:NO  animated:YES];
        [USERDEFAULT setBool:NO forKey:@"SwitchOpen"];
    }else{
        [self.wifiSwitch setOn:YES  animated:YES];
        [USERDEFAULT setBool:YES forKey:@"SwitchOpen"];
    }
}

- (void)setCornerAndBorder
{
    self.iconImageView.layer.cornerRadius = 32.0f;
    self.iconImageView.layer.masksToBounds = YES;
    self.iconImageView.layer.borderColor = rgb(151.0f, 151.0f, 151.0f).CGColor;
    self.iconImageView.layer.borderWidth = 1.0f;

    self.exitBtn.layer.cornerRadius = 4.0f;
    self.exitBtn.layer.masksToBounds = YES;
    self.exitBtn.layer.borderWidth = 1.0f;
    self.exitBtn.layer.borderColor = rgb(44.0f, 126.0f, 194.0f).CGColor;
}

#pragma  mark - 更换头像
- (IBAction)changeIconClick:(id)sender {

    UIActionSheet *chooseImageSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照", @"从手机相册选择", nil];
    [chooseImageSheet showInView:self.view];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    switch (buttonIndex) {
     case 0://Take picture

         if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
         picker.sourceType = UIImagePickerControllerSourceTypeCamera;
         NSString *mediaType = AVMediaTypeVideo;
         AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
             if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) {

             return;
                 }
         } else {

         }
         [self presentViewController:picker animated:YES completion:nil];
         break;

     case 1://From album
         picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;


         [self presentViewController:picker animated:YES completion:nil];
         break;

     default:

     break;
     }
 }

 - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
     [picker dismissViewControllerAnimated:YES completion:nil];
//     [MBProgressHUD showHUDAddedTo:self.view animated:YES];

// 上传@"http://rapapi.org/mockjsdata/25040/api/upload"
    [[HttpClient shareInstanceClient] POST:TrainTreeMineUploadURL parameters:@{@"file":@"1"} constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {

//        NSData *data = UIImagePNGRepresentation(image);
        NSData *data = UIImageJPEGRepresentation(image,0.3);
        
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            // 设置时间格式
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"%@.png", str];

        [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"image/png"];

    } progress:^(NSProgress * _Nonnull uploadProgress) {
        NSLog(@"%f",1.0 * uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"上传成功 %@", responseObject);
        NSString *finalImgUrl = @"";
        // 在返回的图片url之前拼接
        if(responseObject){
            finalImgUrl = [NSString stringWithFormat:@"%@%@",TrainTreeFileImgURL,responseObject[@"d"]];
        }
        [MineRequestManager modifyMineAvatarWithAvatarUrl:finalImgUrl userId:@([[Session shareSession].userId integerValue])  Response:^(id JSONData, NSError *error, NSURLSessionDataTask *dataTask) {
            if ([JSONData[@"c"] intValue] == 0) {
                [SVProgressHUD showSuccessWithStatus:@"修改头像成功"];
            }
        }];

        [SVProgressHUD showWithStatus:responseObject[@"m"]];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"上传失败 %@", error);
    }];

    self.iconImageView.image = image;

}


- (void)backToLastPage
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma  退出登录
- (IBAction)exitClick:(id)sender {
    [Session exit];
    [self backToLastPage];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
